//
//  AppDelegate.m
//  rrbi
//
//  Created by kyjun on 16/4/26.
//
//

#import "AppDelegate.h"
#import "NewOrder.h"
#import "ProcessedOrder.h"
#import "StoreMange.h"
#import "Setting.h"
#import "JPUSHService.h"
#import <AFNetworking/AFNetworkActivityIndicatorManager.h>
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <IQKeyboardManager/IQToolbar.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AdSupport/AdSupport.h>

@interface AppDelegate ()

@property(nonatomic,strong) UITabBarController* tabBarController;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc]initWithFrame:SCREEN];
    self.window.backgroundColor = theme_default_color;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
    {
        self.window.clipsToBounds = YES;
        [[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleLightContent];
        
        UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
        if(orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight)
        {
            self.window.frame =  CGRectMake(20, 0,self.window.frame.size.width-20,self.window.frame.size.height);
            self.window.bounds = CGRectMake(20, 0, self.window.frame.size.width, self.window.frame.size.height);
        } else
        {
            self.window.frame =  CGRectMake(0,20,self.window.frame.size.width,self.window.frame.size.height-20);
            self.window.bounds = CGRectMake(0, 20, self.window.frame.size.width, self.window.frame.size.height);
        }
    }
    [self layoutTabar];
    self.tabBarController = [[UITabBarController alloc]init];
    
    [self.tabBarController setViewControllers:@[
                                                [[UINavigationController alloc]initWithRootViewController:[[NewOrder alloc]init]],
                                                [[UINavigationController alloc]initWithRootViewController:[[ProcessedOrder alloc]init]],
                                                [[UINavigationController alloc]initWithRootViewController:[[StoreMange alloc]init]],
                                                [[UINavigationController alloc]initWithRootViewController:[[Setting alloc]init]],
                                                ]];
    
    self.window.rootViewController = self.tabBarController;
    
    [self.window makeKeyAndVisible];
    
    [self startJPush:launchOptions];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required
    [JPUSHService handleRemoteNotification:userInfo];
    [self handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    [self handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification  completionHandler:(void (^)())completionHandler {
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
}
#endif

#pragma mark =====================================================  Tabar layout
-(void)layoutTabar{
    NSDictionary *navbarTitleTextAttributes = @{NSForegroundColorAttributeName:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0],NSFontAttributeName:[UIFont boldSystemFontOfSize:17.f]};
    [[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];
    [[UINavigationBar appearance] setBackgroundColor:theme_navigation_color];
    [[UINavigationBar appearance] setBarTintColor:theme_navigation_color];
    [[UINavigationBar appearance] setTintColor:theme_default_color];
    [[UINavigationBar appearance] setBarStyle:UIBarStyleBlack];
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
    // [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"icon-nav"] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
    
    [[UIToolbar appearance] setBackgroundColor:theme_navigation_color];
    [[UIToolbar appearance] setBarTintColor:theme_navigation_color];
    [[UIToolbar appearance] setTintColor:theme_default_color];
    
    
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:42/255.0 green:42/255.0 blue:42/255.0 alpha:1.0],NSFontAttributeName:[UIFont systemFontOfSize:12.f]} forState:UIControlStateNormal];
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:30/255.f green:147/255.f blue:238/255.f alpha:1.0],NSFontAttributeName:[UIFont systemFontOfSize:12.f]} forState:UIControlStateSelected];
    
    [[UITableView appearance] setBackgroundColor:theme_table_bg_color];
    [[UICollectionView appearance] setBackgroundColor:theme_table_bg_color];
    
    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
    [NSURLCache setSharedURLCache:URLCache];
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    [[IQToolbar appearance] setBarTintColor:theme_navigation_color];
    [[IQToolbar appearance] setTintColor:theme_default_color];
}

#pragma mark =====================================================  设置极光推送
-(void)startJPush:(NSDictionary*)launchOptions{
    
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    /*接收自定义消息 NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
     [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];*/
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert) categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert) categories:nil];
    }
    
    /* if (DEBUG) {
     [JPUSHService setupWithOption:launchOptions appKey:appKey
     channel:nil
     apsForProduction:NO advertisingIdentifier:advertisingId];
     }else{*/
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:nil
                 apsForProduction:YES  advertisingIdentifier:advertisingId];
    /*}*/
    
}

#pragma mark =====================================================  远程通知
/**
 *  接收通知
 *
 *  @param remoteInfo
 */
-(void)handleRemoteNotification:(NSDictionary *)remoteInfo{
    NSLog(@"通知:%@",remoteInfo);
    if(![WMHelper isNULLOrnil:remoteInfo])
    {
        NSString* notificationType = [remoteInfo objectForKey:@"qs_type"];
        if([notificationType isEqualToString:@"at"]){
            [self PayAudio:@"push_to_order.mp3"];
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationRemoteAt object:nil];
        }else if([notificationType isEqualToString:@"pm"]){
            [self PayAudio:@"push_by_system.mp3"];
            
        }else{
            
        }
    }
}

-(void)PayAudio:(NSString*)fileName{
    NSString *path = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], fileName];
    
    SystemSoundID soundID;
    
    NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
    
    //Use audio sevices to create the sound
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);
    //Use audio services to play the sound
    AudioServicesPlaySystemSound(soundID);
}

@end
